from flask import Blueprint, render_template, redirect, url_for, session, flash, request, make_response
import mysql.connector
from auth import login_required, get_db_connection
from datetime import datetime
import csv
from io import StringIO  # 用于生成CSV文件

user_bp = Blueprint('user', __name__)


# 用户登录
@user_bp.route('/login', methods=['GET', 'POST'])
def user_login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)
        cursor.execute("SELECT * FROM users WHERE username = %s", (username,))
        user = cursor.fetchone()
        cursor.close()
        conn.close()

        # 实际应用中应该使用密码哈希验证
        if user and user['password'] == password:
            session['user_id'] = user['id']
            session['username'] = user['username']
            session['role'] = user['role']
            flash('登录成功！', 'success')

            if user['role'] == 'admin':
                return redirect(url_for('admin.dashboard'))
            else:
                return redirect(url_for('user.dashboard'))
        else:
            flash('用户名或密码错误', 'danger')

    return render_template('user/login.html')


# 用户注册
@user_bp.route('/register', methods=['GET', 'POST'])
def user_register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        email = request.form['email']
        phone = request.form['phone']

        conn = get_db_connection()
        cursor = conn.cursor()

        try:
            cursor.execute(
                "INSERT INTO users (username, password, email, phone) VALUES (%s, %s, %s, %s)",
                (username, password, email, phone)
            )
            conn.commit()
            flash('注册成功，请登录', 'success')
            return redirect(url_for('user.user_login'))
        except mysql.connector.Error as err:
            flash(f'注册失败: {err}', 'danger')
        finally:
            cursor.close()
            conn.close()

    return render_template('user/register.html')


# 用户仪表板
@user_bp.route('/dashboard')
@login_required
def dashboard():
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 获取用户预订信息
    cursor.execute("""
        SELECT b.*, r.name as room_name, r.price 
        FROM bookings b 
        JOIN rooms r ON b.room_id = r.id 
        WHERE b.user_id = %s 
        ORDER BY b.created_at DESC
    """, (session['user_id'],))
    bookings = cursor.fetchall()

    # 获取用户账单
    cursor.execute("""
        SELECT bl.*, b.check_in, b.check_out 
        FROM bills bl 
        JOIN bookings b ON bl.booking_id = b.id 
        WHERE b.user_id = %s
    """, (session['user_id'],))
    bills = cursor.fetchall()

    # 获取用户反馈
    cursor.execute("SELECT * FROM feedbacks WHERE user_id = %s ORDER BY created_at DESC", (session['user_id'],))
    feedbacks = cursor.fetchall()

    cursor.close()
    conn.close()

    return render_template('user/dashboard.html',
                           bookings=bookings,
                           bills=bills,
                           feedbacks=feedbacks)


# 房间搜索
@user_bp.route('/search_rooms', methods=['GET'])
@login_required
def search_rooms():
    # 获取搜索参数
    keyword = request.args.get('keyword', '').strip()
    price_range = request.args.get('price_range', 'all')
    room_type = request.args.get('room_type', 'all')
    capacity = request.args.get('capacity', 'all')

    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 构建查询条件
    query = "SELECT * FROM rooms WHERE status = 'available'"
    params = []

    # 添加关键词搜索条件
    if keyword:
        query += " AND (name LIKE %s OR description LIKE %s)"
        search_term = f"%{keyword}%"
        params.extend([search_term, search_term])

    # 添加价格范围条件
    if price_range != 'all':
        if price_range == '0-200':
            query += " AND price BETWEEN 0 AND 200"
        elif price_range == '200-500':
            query += " AND price BETWEEN 200 AND 500"
        elif price_range == '500-1000':
            query += " AND price BETWEEN 500 AND 1000"
        elif price_range == '1000+':
            query += " AND price >= 1000"

    # 添加房间类型条件
    if room_type != 'all':
        query += " AND room_type = %s"
        params.append(room_type)

    # 添加容纳人数条件
    if capacity != 'all':
        if capacity == '1':
            query += " AND capacity = 1"
        elif capacity == '2':
            query += " AND capacity = 2"
        elif capacity == '3':
            query += " AND capacity BETWEEN 3 AND 4"
        elif capacity == '5+':
            query += " AND capacity >= 5"

    cursor.execute(query, params)
    rooms = cursor.fetchall()
    cursor.close()
    conn.close()

    # 传递搜索参数以便在模板中保持筛选状态
    search_params = {
        'keyword': keyword,
        'price_range': price_range,
        'room_type': room_type,
        'capacity': capacity
    }

    return render_template('user/book.html', rooms=rooms, search_params=search_params)


# 房间预订
@user_bp.route('/book', methods=['GET', 'POST'])
@login_required
def book_room():
    if request.method == 'POST':
        room_id = request.form['room_id']
        check_in = request.form['check_in']
        check_out = request.form['check_out']
        guests = request.form['guests']

        conn = get_db_connection()
        cursor = conn.cursor(dictionary=True)

        # 获取房间价格
        cursor.execute("SELECT price FROM rooms WHERE id = %s", (room_id,))
        room = cursor.fetchone()

        if room:
            # 计算总价
            check_in_date = datetime.strptime(check_in, '%Y-%m-%d')
            check_out_date = datetime.strptime(check_out, '%Y-%m-%d')
            nights = (check_out_date - check_in_date).days
            total_price = room['price'] * nights

            # 创建预订
            cursor.execute("""
                INSERT INTO bookings (user_id, room_id, check_in, check_out, guests, total_price)
                VALUES (%s, %s, %s, %s, %s, %s)
            """, (session['user_id'], room_id, check_in, check_out, guests, total_price))

            booking_id = cursor.lastrowid

            # 创建账单
            cursor.execute("""
                INSERT INTO bills (booking_id, amount) VALUES (%s, %s)
            """, (booking_id, total_price))

            # 更新房间状态为已预订
            cursor.execute("UPDATE rooms SET status = 'booked' WHERE id = %s", (room_id,))

            conn.commit()
            cursor.close()
            conn.close()

            flash('预订成功！', 'success')
            return redirect(url_for('user.dashboard'))

    # GET请求 - 显示可预订房间
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)
    cursor.execute("SELECT * FROM rooms WHERE status = 'available'")
    rooms = cursor.fetchall()
    cursor.close()
    conn.close()

    return render_template('user/book.html', rooms=rooms, search_params={})


# 取消预订
@user_bp.route('/cancel_booking/<int:booking_id>')
@login_required
def cancel_booking(booking_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 获取预订对应的房间ID
    cursor.execute("SELECT room_id FROM bookings WHERE id = %s AND user_id = %s",
                   (booking_id, session['user_id']))
    booking = cursor.fetchone()

    if booking:
        # 更新预订状态为已取消
        cursor.execute("UPDATE bookings SET status = 'cancelled' WHERE id = %s AND user_id = %s",
                       (booking_id, session['user_id']))

        # 将房间状态改回可预订
        cursor.execute("UPDATE rooms SET status = 'available' WHERE id = %s", (booking['room_id'],))

        conn.commit()
        flash('预订已取消', 'success')
    else:
        flash('无法取消预订', 'danger')

    cursor.close()
    conn.close()

    return redirect(url_for('user.dashboard'))


# 支付账单
@user_bp.route('/pay_bill/<int:bill_id>')
@login_required
def pay_bill(bill_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 验证账单是否属于当前用户
    cursor.execute("""
        SELECT b.id FROM bills b
        JOIN bookings bo ON b.booking_id = bo.id
        WHERE b.id = %s AND bo.user_id = %s
    """, (bill_id, session['user_id']))

    bill = cursor.fetchone()

    if bill:
        cursor.execute("UPDATE bills SET status = 'paid', paid_at = NOW() WHERE id = %s", (bill_id,))
        conn.commit()
        flash('支付成功！', 'success')
    else:
        flash('无法找到该账单或没有权限操作', 'danger')

    cursor.close()
    conn.close()

    return redirect(url_for('user.dashboard'))


# 提交问题反馈
@user_bp.route('/feedback', methods=['GET', 'POST'])
@login_required
def submit_feedback():
    if request.method == 'POST':
        title = request.form['title']
        description = request.form['description']

        conn = get_db_connection()
        cursor = conn.cursor()

        cursor.execute("""
            INSERT INTO feedbacks (user_id, title, description) 
            VALUES (%s, %s, %s)
        """, (session['user_id'], title, description))

        conn.commit()
        cursor.close()
        conn.close()

        flash('问题反馈已提交', 'success')
        return redirect(url_for('user.dashboard'))

    return render_template('user/feedback.html')


# 下载发票（修复后的核心部分）
@user_bp.route('/download-invoice/<int:bill_id>')
@login_required
def download_invoice(bill_id):
    conn = get_db_connection()
    cursor = conn.cursor(dictionary=True)

    # 查询账单信息（关联预订和用户表，确保只能下载自己的发票）
    cursor.execute("""
        SELECT b.*, bo.check_in, bo.check_out, r.name as room_name,
               u.username, u.email 
        FROM bills b
        JOIN bookings bo ON b.booking_id = bo.id
        JOIN rooms r ON bo.room_id = r.id
        JOIN users u ON bo.user_id = u.id
        WHERE b.id = %s AND bo.user_id = %s
    """, (bill_id, session['user_id']))

    bill = cursor.fetchone()
    cursor.close()
    conn.close()

    # 验证账单是否存在且属于当前用户
    if not bill:
        flash('发票不存在或没有权限访问', 'danger')
        return redirect(url_for('user.dashboard'))

    # 生成CSV格式的发票
    output = StringIO()
    writer = csv.writer(output)

    # 写入发票内容
    writer.writerow(['酒店预订发票'])
    writer.writerow([''])
    writer.writerow(['发票编号:', f"INV-{bill['id']}"])
    writer.writerow(['用户信息:', bill['username'], bill['email']])
    writer.writerow(['房间信息:', bill['room_name']])
    writer.writerow(['入住日期:', bill['check_in']])
    writer.writerow(['退房日期:', bill['check_out']])
    writer.writerow(['总金额:', f"¥{bill['amount']}"])
    writer.writerow(['支付状态:', '已支付' if bill['status'] == 'paid' else '未支付'])
    writer.writerow(['支付时间:', bill['paid_at'] if bill['paid_at'] else '未支付'])

    # 准备下载响应
    output.seek(0)
    response = make_response(output.getvalue())
    response.headers["Content-Disposition"] = f"attachment; filename=invoice_{bill_id}.csv"
    response.headers["Content-type"] = "text/csv"

    return response


# 用户退出
@user_bp.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出', 'info')
    return redirect(url_for('index'))
